<template>
  <div ref="mapContainer" style="width: 100%; height: 500px;"></div>
</template>

<script setup lang="ts">
import { onMounted, ref, nextTick, onUnmounted } from 'vue'
import feedback from '@/utils/feedback'

const mapContainer = ref<HTMLElement | null>(null)
let map: any = null

const init = () => {
  if(!mapContainer.value) return
  map = new TMap.Map(mapContainer.value, {
    center: new TMap.LatLng(39.916527, 116.397128),
    zoom: 12
  })
}

onMounted(() => {
  const key = import.meta.env.VITE_TMAP_KEY
  if(!key){
    feedback.msgError('缺少腾讯地图 Key 配置(VITE_TMAP_KEY)')
    return
  }
  if (window.TMap) {
    nextTick(init)
    return
  }
  const script = document.createElement('script')
  script.src = `https://map.qq.com/api/gljs?v=1.exp&key=${key}`
  script.onload = () => {
    if (window.TMap) nextTick(init)
    else feedback.msgError('腾讯地图 API 加载失败')
  }
  script.onerror = () => feedback.msgError('腾讯地图 API 脚本加载失败')
  document.head.appendChild(script)
})

onUnmounted(()=>{
  map = null
})
</script>

<style scoped>
/* 样式可以根据需求自定义 */
</style>
  